package com.popreal.scheduler.helper;

import redis.clients.jedis.Jedis;

import com.popreal.scheduler.bae.BAEConfig;
import com.popreal.scheduler.interceptor.BaseInterceptor;
import com.popreal.shop.helper.RedisHelper;
import com.popreal.shop.helper.RedisHelper.RedisCallback;

public class BAERedisHelper {
	
	private static BAEConfig baeConfig;
	
	public static void setBaeConfig(BAEConfig baeConfig) {
		BAERedisHelper.baeConfig = baeConfig;
	}

	/**
	 * true 表示 BAE 环境
	 */
	public static final boolean isBAE;

	static {
		isBAE = System.getenv("SERVER_SOFTWARE") != null;
	}
	
	public static <T> T use(RedisCallback<T> redisCallback){
		if(!isBAE) {
			RedisHelper redisHelper = BaseInterceptor.springContext.getBean(RedisHelper.class);
			return redisHelper.use(redisCallback);
		}
		
		// BAE
        Jedis jedis = new Jedis("redis.duapp.com", 80);
        jedis.connect();
        jedis.auth(baeConfig.getAk() + "-" + baeConfig.getSk() + "-" + baeConfig.getRedisDbname());
        try {
            return redisCallback.execute(jedis);
        } finally {
            if (null != jedis) {
            	jedis.close();
            }
        }
    }
	
}
